package com.lixin.smartclassroom.ui.home.tab5.fragment

import android.graphics.Color
import android.net.Uri
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.ViewGroup
import com.drake.net.utils.scopeNetLife
import com.lixin.smartclassroom.api.bindstudentlist
import com.lixin.smartclassroom.api.childclasslist
import com.lixin.smartclassroom.api.classlist
import com.lixin.smartclassroom.api.customerdetail
import com.lixin.smartclassroom.api.myjoinclass
import com.lixin.smartclassroom.api.updatecustomer
import com.lixin.smartclassroom.api.uploadFile
import com.lixin.smartclassroom.api.zuijinstudent
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.FragmentTab1Binding
import com.lixin.smartclassroom.databinding.FragmentTab5Binding
import com.lixin.smartclassroom.ext.child_id
import com.lixin.smartclassroom.ext.user_role
import com.lixin.smartclassroom.ui.home.adapter.recentAttend
import com.lixin.smartclassroom.ui.home.tab5.activity.AboutUsAct
import com.lixin.smartclassroom.ui.home.tab5.activity.ContactUsAct
import com.lixin.smartclassroom.ui.home.tab5.activity.DatabaseAct
import com.lixin.smartclassroom.ui.home.tab5.activity.EventManagementAct
import com.lixin.smartclassroom.ui.home.tab5.activity.ExcitingMomentsManagerAct
import com.lixin.smartclassroom.ui.home.tab5.activity.MessageBoardAct
import com.lixin.smartclassroom.ui.home.tab5.activity.MyClassAct
import com.lixin.smartclassroom.ui.home.tab5.activity.QuestionnaireAct
import com.lixin.smartclassroom.ui.home.tab5.activity.RecentlyEventMoreActivity
import com.lixin.smartclassroom.ui.home.tab5.activity.SetAct
import com.lixin.smartclassroom.ui.login.BindStudentAct
import com.lixin.smartclassroom.utils.LoginManager
import com.lixinkeji.base.BaseFragment
import com.lixinkeji.extension.commonDialog
import com.lixinkeji.extension.dp2px
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.loadCircle
import com.lixinkeji.extension.loadRound
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.setRoundRectBg
import com.lixinkeji.extension.start
import com.lixinkeji.extension.visible
import com.lixinkeji.utils.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import java.io.File

/**
 * Description
 * Author: lwc
 * Date:2023/12/5 15:25
 */
class Tab5Fragment : BaseFragment<FragmentTab5Binding>() {
    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?
    ) = FragmentTab5Binding.inflate(inflater)

    private lateinit var listBean: ArrayList<DataListBean>
    private lateinit var eventList: ArrayList<DataListBean>

    override fun iniView() {
        getCustomerdetail()
    }

    private fun getRecentlyEvent() {
        scopeNetLife {
            eventList = ArrayList()
            eventList.addAll(zuijinstudent(1, 3)!!)
            if (eventList.size == 0) {
                binding.llStudent.gone()
            } else {
                binding.llStudent.visible()
                binding.recycler.recentAttend().models = eventList

            }

        }
    }

    private fun getClassData(type: String) {
        binding.apply {
            scopeNetLife {
                var listBean = when (type) {
                    "3" -> childclasslist(1, 1000, requireContext().child_id)
                    else -> myjoinclass(1, 1000, type)
                }

                when (requireContext().user_role) {
                    1 -> {
                        scopeNetLife {
                            var studentNum = 0
                            studentNum = bindstudentlist(1, 1000)?.size!!
                            if (studentNum == 0) {
                                tvStudent.text = "暂无学生"
                                btnBind.text = "点击绑定"
                            } else {
                                tvStudent.text = "已绑定" + studentNum + "个学生"
                                btnBind.text = "立即查看"
                            }

                        }
                    }

                    else -> {
                        if (listBean == null || listBean.size == 0) {
                            tvStudent.text = "暂无班级"
                            btnBind.text = "点击加入"
                        } else {
                            tvStudent.text = "已加入" + listBean.size + "个班级"
                            btnBind.text = "立即查看"
                        }
                    }
                }

            }

        }

    }

    private fun getCustomerdetail() {
        scopeNetLife {
            var baseBean = customerdetail()
            if (baseBean.result == "0") {
                binding.apply {
                    tvName.text = baseBean.name
                    if (baseBean.image != null)
                        headImg.loadCircle(baseBean.image!!)
                    when (requireContext().user_role) {
                        1 -> tvContent.text =
                            "手机号：" + baseBean.phone + "  互动码：" + baseBean.hudong

                        2 -> tvContent.text =
                            "学号：" + baseBean.xuehao + "  互动码：" + baseBean.hudong

                        3 -> tvContent.text = "互动码：" + baseBean.hudong
                    }

                }
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (!hidden) {
            binding.apply {

                btnBind.setRoundRectBg(
                    Color.parseColor("#FEEBCB"), requireActivity().dp2px(13f).toInt()
                )
                tvRole.setRoundRectBg(
                    Color.parseColor("#FCC93D"), requireActivity().dp2px(3f).toInt()
                )
                when (requireActivity().user_role) {
                    1 -> {
                        tvRole.text = "家长"
                        llParent.visible()
                        llTeacher.gone()
                        tvMoments.gone()
                        dividerMoments.gone()
                        llStudent.gone()
                        getClassData("3")
                    }

                    2 -> {
                        tvRole.text = "学生"
                        llParent.gone()
                        llTeacher.gone()
                        tvMoments.gone()
                        dividerMoments.gone()
                        getClassData("1")
                        getRecentlyEvent()
                    }

                    3 -> {
                        tvRole.text = "老师"
                        llParent.gone()
                        llTeacher.visible()
                        llStudent.gone()
                        getClassData("2")
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        binding.apply {

            btnBind.setRoundRectBg(
                Color.parseColor("#FEEBCB"), requireActivity().dp2px(13f).toInt()
            )
            tvRole.setRoundRectBg(
                Color.parseColor("#FCC93D"), requireActivity().dp2px(3f).toInt()
            )
            when (requireActivity().user_role) {
                1 -> {
                    tvRole.text = "家长"
                    llParent.visible()
                    llTeacher.gone()
                    tvMoments.gone()
                    dividerMoments.gone()
                    llStudent.gone()
                    getClassData("3")
                }

                2 -> {
                    tvRole.text = "学生"
                    llParent.gone()
                    llTeacher.gone()
                    tvMoments.gone()
                    dividerMoments.gone()
                    getClassData("1")
                    getRecentlyEvent()
                }

                3 -> {
                    tvRole.text = "老师"
                    llParent.gone()
                    llTeacher.visible()
                    llStudent.gone()
                    getClassData("2")
                }
            }
        }
    }

    override fun onClick() {
        binding.apply {
            llMyClass.onClick {
                when (requireContext().user_role) {
                    2, 3 -> start(MyClassAct::class.java)
                    else -> {
                        start(BindStudentAct::class.java) {
                            putExtra("type", "2")
                        }
                    }
                }
            }
            tvWenJuan.onClick {
                start(QuestionnaireAct::class.java)
            }
            tvLiuyanban.onClick {
                start(MessageBoardAct::class.java)
            }
            tvContactUs.onClick {
                start(ContactUsAct::class.java)
            }
            tvAboutUs.onClick {
                start(AboutUsAct::class.java)
            }
            tvSet.onClick {
                start(SetAct::class.java)
            }
            tvEventManagement.onClick {
                start(EventManagementAct::class.java)
            }

            tvDatabase.onClick {
                start(DatabaseAct::class.java)
            }
            tvMoments.onClick {
                start(ExcitingMomentsManagerAct::class.java)
            }
            tvRole.onClick {
                requireContext().commonDialog("切换账号", "是否切换账号", "取消", "确定", onSure = {
                    LoginManager.logout(requireActivity())
                })

            }
            headImg.onClick {
                selectPicture()
            }

            tvMore.onClick {
                start(RecentlyEventMoreActivity::class.java)
            }
        }
    }

    private fun selectPicture() {
        PictureSelector.create(requireActivity())
            .openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(1)
            .setMinSelectNum(0)// 最小选择数量
            .setImageSpanCount(4)// 每行显示个数
            .setSelectionMode(SelectModeConfig.SINGLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
            .isPreviewImage(true)// 是否可预览图片
            .isCameraAroundState(true)// 是否显示拍照按钮
            .isSelectZoomAnim(true)// 图片列表点击 缩放效果 默认true
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {

                    if (result != null) {
                        if (result.size > 0) {
                            binding.headImg.loadCircle(result?.get(0)?.realPath!!)
                            var file: File
                            if (result[0].path!!.contains("content:")) {
                                var res = ""
                                var proj = arrayOf(MediaStore.Images.Media.DATA)
                                val cursor = requireContext().contentResolver.query(
                                    Uri.parse(result[0].path!!),
                                    proj,
                                    null,
                                    null,
                                    null
                                );
                                if (cursor?.moveToFirst() == true) {
                                    val column_index =
                                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                                    res = cursor.getString(column_index);
                                }
                                cursor?.close()
                                file = File(res)
                            } else {
                                file = File(result[0].path!!)
                            }

                            scopeNetLife {
                                val baseBean = uploadFile(file)
                                if (baseBean.result == "0") {
                                    scopeNetLife {
                                        updatecustomer(baseBean.url!!)
                                        requireContext().saveSuccessDialog("头像修改成功")
                                    }
                                }
                            }
                        }
                    }

                }

                override fun onCancel() {

                }
            })

    }
}